package com.laiketui.common.service.dubbo.plugin.bargain;

import com.alibaba.fastjson.JSON;
import com.laiketui.common.annotation.HandlerOrderType;
import com.laiketui.common.mapper.*;
import com.laiketui.common.utils.tool.cache.RedisDataTool;
import com.laiketui.common.utils.tool.data.GoodsDataUtils;
import com.laiketui.common.utils.tool.str.StringUtils;
import com.laiketui.domain.lktconst.DictionaryConst;
import com.laiketui.domain.lktconst.ErrorCode;
import com.laiketui.domain.order.BargainOrderModel;
import com.laiketui.domain.order.OrderDetailsModel;
import com.laiketui.domain.order.OrderModel;
import com.laiketui.domain.plugin.group.GoGroupOrderModel;
import com.laiketui.domain.product.BargainGoodsModel;
import com.laiketui.domain.product.StockModel;
import com.laiketui.domain.user.User;
import com.laiketui.domain.user.UserAddress;
import com.laiketui.domain.vo.OrderVo;
import com.laiketui.domain.vo.order.*;
import com.laiketui.domain.vo.plugin.group.ProductInfoParamVo;
import com.laiketui.common.api.PublicAddressService;
import com.laiketui.common.api.PublicMemberService;
import com.laiketui.common.api.PublicOrderService;
import com.laiketui.common.api.PubliceService;
import com.laiketui.common.api.order.OrderDubboService;
import com.laiketui.core.cache.RedisUtil;
import com.laiketui.core.exception.LaiKeAPIException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.math.BigDecimal;
import java.util.*;

/**
 * 砍价订单流程
 *
 * @author Trick
 * @date 2021/4/20 17:44
 */
@HandlerOrderType(type = DictionaryConst.OrdersType.ORDERS_HEADER_KJ)
@Service
public class BargainOrderServiceImpl implements OrderDubboService {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private UserBaseMapper userBaseMapper;

    @Autowired
    private PublicOrderService publicOrderService;

    @Autowired
    private BargainGoodsModelMapper bargainGoodsModelMapper;

    @Autowired
    private ProductListModelMapper productListModelMapper;

    @Autowired
    private BargainOrderModelMapper bargainOrderModelMapper;

    @Autowired
    private OrderModelMapper orderModelMapper;

    @Autowired
    private OrderDetailsModelMapper orderDetailsModelMapper;

    @Autowired
    private PubliceService publiceService;

    @Autowired
    private PublicAddressService publicAddressService;

    @Autowired
    private PublicMemberService publicMemberService;

    @Autowired
    private ConfiGureModelMapper confiGureModelMapper;

    @Autowired
    private StockModelMapper stockModelMapper;

    @Override
    public Map<String, Object> settlement(OrderVo vo) {
        Map<String, Object> resultMap = new HashMap<>(16);
        try {
            User user = RedisDataTool.getRedisUserCache(vo.getAccessId(), redisUtil, true);
            //处理参数 [{"pid":"1271"},{"cid":"16630"},{"num":1},{"bargain":true},{"bargain_id":"10"},{"order_no":"KJ0285250293"}]
            String goodsParmaStr = vo.getProductsInfo().substring(1, vo.getProductsInfo().length() - 1);
            goodsParmaStr = goodsParmaStr.replace("{", "").replace("}", "");
            goodsParmaStr = "{" + goodsParmaStr + "}";
            ProductInfoParamVo productInfoParamVo;
            try {
                productInfoParamVo = JSON.parseObject(goodsParmaStr, ProductInfoParamVo.class);
            } catch (Exception e) {
                e.printStackTrace();
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_CSCW, "参数错误");
            }

            Map<String, Object> parmaMap = new HashMap<>(16);
            //是否有收货地址标识
            int isAddress = DictionaryConst.WhetherMaven.WHETHER_NO;
            //用户是否设置支付密码标识
            int isSetPayPwd = DictionaryConst.WhetherMaven.WHETHER_NO;
            user = userBaseMapper.selectByPrimaryKey(user.getId());
            if (!StringUtils.isEmpty(user.getPassword())) {
                isSetPayPwd = DictionaryConst.WhetherMaven.WHETHER_OK;
            }

            //获取砍价信息
            BargainGoodsModel bargainGoodsModel = new BargainGoodsModel();
            bargainGoodsModel.setStore_id(vo.getStoreId());
            bargainGoodsModel.setId(productInfoParamVo.getActivityNo());
            bargainGoodsModel = bargainGoodsModelMapper.selectOne(bargainGoodsModel);
            if (bargainGoodsModel == null) {
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_SJYC, "数据异常");
            }
            //获取收货地址信息
            UserAddress userAddress = publicAddressService.findAddress(vo.getStoreId(), user.getUser_id(), vo.getAddressId());
            BigDecimal freightPrice = BigDecimal.ZERO;

            //获取商品信息
            parmaMap.put("store_id", vo.getStoreId());
            parmaMap.put("pid", bargainGoodsModel.getGoods_id());
            parmaMap.put("attrId", bargainGoodsModel.getAttr_id());
            List<Map<String, Object>> goodsInfo = productListModelMapper.getProductListDynamic(parmaMap);

            //获取结算金额
            BigDecimal orderPrice = BigDecimal.ZERO;
            //商品运费模板id
            Integer goodsTemplateId = null;
            //商品价格
            BigDecimal goodsPrice;
            for (Map<String, Object> map : goodsInfo) {
                //构造数据结构
                List<Map<String, Object>> goodsList = new ArrayList<>();
                Map<String, Object> tempGoodsMap = new HashMap<>(16);
                //填充商品信息
                tempGoodsMap.put("img", publiceService.getImgPath(map.get("img").toString(), vo.getStoreId()));
                tempGoodsMap.put("pid", map.get("id"));
                tempGoodsMap.put("price", bargainGoodsModel.getMin_price());
                tempGoodsMap.put("brand_id", bargainGoodsModel.getId());
                tempGoodsMap.put("num", 1);
                tempGoodsMap.put("pro_name", map.get("product_title"));
                tempGoodsMap.put("freight_price", map.get("freight"));
                tempGoodsMap.put("size", GoodsDataUtils.getProductSkuValue(map.get("attribute").toString()));
                goodsList.add(tempGoodsMap);

                if (map.containsKey("freight") && !StringUtils.isEmpty(map.get("freight"))) {
                    goodsTemplateId = Integer.parseInt(map.get("freight").toString());
                }
                freightPrice = publicOrderService.getFreight(goodsTemplateId, userAddress);
                if (userAddress != null) {
                    //未设置免邮,计算运费
                    freightPrice = publicOrderService.getFreight(goodsTemplateId, userAddress);
                    orderPrice = orderPrice.add(freightPrice);
                    isAddress = DictionaryConst.WhetherMaven.WHETHER_OK;
                }
                map.put("products_num", 1);
                map.put("freight_price", vo.getStoreId());
                map.put("product_total", new BigDecimal(map.get("price").toString()));
                //填充店铺信息
                map.put("shop_id", map.get("mchId"));
                map.put("shop_name", map.get("mch_name"));
                map.put("shop_logo", map.get("logo"));
                map.put("list", goodsList);
            }
            //商品价格
            goodsPrice = bargainGoodsModel.getMin_price();
            orderPrice = orderPrice.add(goodsPrice);

            //计算会员特惠
            BigDecimal gradeRate = new BigDecimal(publicMemberService.getMemberGradeRate(DictionaryConst.OrdersType.ORDERS_HEADER_KJ, user.getUser_id(), vo.getStoreId()) + "");

            resultMap.put("status", 1);
            resultMap.put("address", userAddress);
            resultMap.put("freight", freightPrice);
            resultMap.put("password_status", isSetPayPwd);
            //商品信息
            resultMap.put("products", goodsInfo);
            //是否有收货地址
            resultMap.put("addemt", isAddress);
            //支付方式配置
            resultMap.put("payment", publicOrderService.getPaymentConfig(vo.getStoreId()));
            //用户余额
            resultMap.put("user_money", user.getMoney());
            resultMap.put("user_name", user.getUser_name());
            //订单价格
            resultMap.put("products_total", orderPrice);
            //最终优惠价格
            resultMap.put("total", orderPrice.multiply(gradeRate));
            //优惠金额
            resultMap.put("grade_rate_amount", orderPrice.subtract(orderPrice.multiply(gradeRate)));
            //会员折扣
            resultMap.put("grade_rate", gradeRate);
            resultMap.put("enterless", true);
        } catch (LaiKeAPIException l) {
            throw l;
        } catch (Exception e) {
            logger.error("获取拼团订单信息 异常", e);
            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLYC, "网络异常", "getPtOrderInfo");
        }
        return resultMap;
    }

    @Transactional
    @Override
    public Map<String, Object> payment(OrderVo vo) {
        Map<String, Object> resultMap = new HashMap<>(16);
        try {
            User user = RedisDataTool.getRedisUserCache(vo.getAccessId(), redisUtil, true);
            //处理参数 [{"pid":"1271"},{"cid":"16630"},{"num":1},{"bargain":true},{"bargain_id":"10"},{"order_no":"KJ0285250293"}]
            String goodsParmaStr = vo.getProductsInfo().substring(1, vo.getProductsInfo().length() - 1);
            goodsParmaStr = goodsParmaStr.replace("{", "").replace("}", "");
            goodsParmaStr = "{" + goodsParmaStr + "}";
            ProductInfoParamVo productInfoParamVo;
            try {
                productInfoParamVo = JSON.parseObject(goodsParmaStr, ProductInfoParamVo.class);
            } catch (Exception e) {
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_CSCW, "参数错误");
            }
            //获取砍价订单信息
            BargainOrderModel bargainOrderModel = new BargainOrderModel();
            bargainOrderModel.setStore_id(vo.getStoreId());
            bargainOrderModel.setBargain_id(vo.getMainId());
            bargainOrderModel.setUser_id(user.getUser_id());
            bargainOrderModel.setGoods_id(productInfoParamVo.getPid());
            bargainOrderModel.setAttr_id(productInfoParamVo.getCid());
            bargainOrderModel = bargainOrderModelMapper.selectOne(bargainOrderModel);
            if (bargainOrderModel == null) {
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_DDBCZ, "订单不存在");
            }

            //获取用户地址
            UserAddress userAddress = publicAddressService.findAddress(vo.getStoreId(), user.getUser_id(), vo.getAddressId());
            if (userAddress == null) {
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_QXZSHDZ, "请选择收货地址");
            }
            OrderModel orderSave = new OrderModel();
            orderSave.setReal_sno(bargainOrderModel.getOrder_no());
            orderSave = orderModelMapper.selectOne(orderSave);
            if (orderSave == null) {
                //刷新用户信息
                user = userBaseMapper.selectByPrimaryKey(user.getId());
                RedisDataTool.refreshRedisUserCache(vo.getAccessId(), user, redisUtil);
                //获取砍价金额
                BigDecimal orderPrice = new BigDecimal(bargainOrderModel.getMin_price().toString());

                //获取商品信息
                Map<String, Object> goodsMap;
                Map<String, Object> parmaMap = new HashMap<>(16);
                parmaMap.put("store_id", vo.getStoreId());
                parmaMap.put("pid", productInfoParamVo.getPid());
                parmaMap.put("attrId", productInfoParamVo.getCid());
                parmaMap.put("active", DictionaryConst.GoodsActive.GOODSACTIVE_POSITIVE_KJ);
                List<Map<String, Object>> goodsInfo = productListModelMapper.getProductListDynamic(parmaMap);
                if (goodsInfo == null || goodsInfo.size() != 1) {
                    throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_CSCW, "参数错误");
                }
                goodsMap = goodsInfo.get(0);
                //商品id
                int goodsId = Integer.parseInt(goodsMap.get("id").toString());
                //商品价格
                BigDecimal goodsPrice = new BigDecimal(goodsInfo.get(0).get("price").toString());
                //商品运费模板id
                int goodsTemplateId = Integer.parseInt(goodsMap.get("freight").toString());
                //商品所属店铺
                int mchId = Integer.parseInt(goodsMap.get("mchId").toString());
                //商品名称
                String goodsName = goodsMap.get("product_title").toString();
                //商品单位
                String unit = goodsMap.get("unit") + "";
                //商品规格
                String attrName = GoodsDataUtils.getProductSkuValue(goodsMap.get("attribute").toString());
                //商品库存
                int stockNum = Integer.parseInt(goodsMap.get("num").toString());
                if (stockNum < 1) {
                    throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_KCBZ, "库存不足");
                }

                //砍价订单待付款状态
                BargainOrderModel bargainOrderUpdate = new BargainOrderModel();
                bargainOrderUpdate.setId(bargainOrderModel.getId());
                bargainOrderUpdate.setStatus(BargainOrderModel.OrderStatus.GO_PAY);
                int row = bargainOrderModelMapper.updateByPrimaryKeySelective(bargainOrderUpdate);
                if (row < 1) {
                    throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_CSCW, "参数错误");
                }

                //生成砍价总订单号
                String orderno = publicOrderService.createOrderNo(DictionaryConst.OrdersType.ORDERS_HEADER_KJ);
                //计算会员特惠
                BigDecimal gradeRate = new BigDecimal(publicMemberService.getMemberGradeRate(DictionaryConst.OrdersType.ORDERS_HEADER_KJ, user.getUser_id(), vo.getStoreId()) + "");
                //计算运费
                BigDecimal freightPrice = publicOrderService.getFreight(goodsTemplateId, userAddress);
                orderPrice = orderPrice.add(freightPrice);
                //拼接店铺
                String mchStr = String.format(",%s,", mchId);
                //添加订单信息
                orderSave = new OrderModel();
                orderSave.setStore_id(vo.getStoreId());
                orderSave.setUser_id(user.getUser_id());
                orderSave.setsNo(orderno);
                orderSave.setReal_sno(bargainOrderModel.getOrder_no());
                orderSave.setName(userAddress.getName());
                orderSave.setMobile(userAddress.getTel());
                orderSave.setNum(productInfoParamVo.getNum());
                orderSave.setSpz_price(goodsPrice);
                orderSave.setZ_price(orderPrice);
                orderSave.setSheng(userAddress.getSheng());
                orderSave.setShi(userAddress.getCity());
                orderSave.setXian(userAddress.getQuyu());
                orderSave.setAddress(userAddress.getAddress());
                orderSave.setPay(vo.getPayType());
                orderSave.setSource(vo.getStoreType());
                orderSave.setSubtraction_id(0);
                orderSave.setOtype(DictionaryConst.OrdersType.ORDERS_HEADER_KJ);
                orderSave.setStatus(GoGroupOrderModel.OrderStatus.NOTPAY);
                orderSave.setPid(productInfoParamVo.getFromapge());
                orderSave.setMch_id(mchStr);
                orderSave.setGrade_rate(gradeRate);
                orderSave.setAdd_time(new Date());
                int count = orderModelMapper.insertSelective(orderSave);
                if (count < 1) {
                    throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_XDSB, "下单失败");
                }
                //详情数据
                OrderDetailsModel orderDetailsSave = new OrderDetailsModel();
                orderDetailsSave.setR_sNo(orderSave.getsNo());
                orderDetailsSave.setStore_id(vo.getStoreId());
                orderDetailsSave.setAfter_discount(orderSave.getZ_price());
                orderDetailsSave.setUser_id(user.getUser_id());
                orderDetailsSave.setP_id(productInfoParamVo.getPid());
                orderDetailsSave.setP_name(goodsName);
                orderDetailsSave.setP_price(orderSave.getSpz_price());
                orderDetailsSave.setNum(orderSave.getNum());
                orderDetailsSave.setSize(attrName);
                orderDetailsSave.setSid(productInfoParamVo.getCid().toString());
                orderDetailsSave.setFreight(freightPrice);
                orderDetailsSave.setUnit(unit);
                orderDetailsSave.setAdd_time(new Date());
                count = orderDetailsModelMapper.insertSelective(orderDetailsSave);
                if (count < 1) {
                    throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_XDSB, "下单失败");
                }
                //修改总库存
                count = productListModelMapper.reduceGoodsStockNum(goodsId, orderDetailsSave.getNum());
                if (count < 1) {
                    logger.error("商品id={} 商品总库存扣减失败 数量{}", productInfoParamVo.getPid(), orderDetailsSave.getNum());
                    throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_XDSB, "下单失败");
                }
                //扣减规格库存
                count = confiGureModelMapper.reduceGoodsStockNum(-orderDetailsSave.getNum(), productInfoParamVo.getCid());
                if (count < 1) {
                    logger.error("商品id={} 规格存扣减失败 数量{}", productInfoParamVo.getPid(), orderDetailsSave.getNum());
                    throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_XDSB, "下单失败");
                }

                //剩余库存
                int totalStockNum = confiGureModelMapper.sumConfigGureNum(productInfoParamVo.getCid());
                //生成记录
                String msg = "%s生成订单所需%s";
                StockModel stockSave = new StockModel();
                stockSave.setType(StockModel.StockType.AGREEMENTTYPE_WAREHOUSING_OUT);
                stockSave.setContent(String.format(msg, "砍价", orderDetailsSave.getNum()));
                stockSave.setTotal_num(totalStockNum);
                stockSave.setFlowing_num(orderDetailsSave.getNum());
                stockSave.setStore_id(vo.getStoreId());
                stockSave.setProduct_id(productInfoParamVo.getPid());
                stockSave.setAttribute_id(productInfoParamVo.getCid());
                stockSave.setUser_id(user.getUser_id());
                stockSave.setAdd_date(new Date());
                count = stockModelMapper.insertSelective(stockSave);
                if (count < 1) {
                    logger.error("商品id={} 库存记录失败 数量{}", productInfoParamVo.getPid(), orderDetailsSave.getNum());
                    throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_XDSB, "下单失败");
                }
            }
            resultMap.put("status", 1);
            resultMap.put("order", orderSave.getsNo());
            resultMap.put("total", orderSave.getZ_price());
            resultMap.put("order_id", orderSave.getId());
        } catch (LaiKeAPIException l) {
            throw l;
        } catch (Exception e) {
            logger.error("创建砍价订单 异常", e);
            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLYC, "网络异常", "payment");
        }
        return resultMap;
    }

    @Override
    public Map<String, Object> updateOrderRemark(OrderVo vo) {
        return null;
    }

    @Override
    public Map<String, Object> splitOrder(OrderVo vo) {
        return null;
    }

    @Override
    public Map<String, Object> returnData(ApplyReturnDataVo vo, MultipartFile file) throws LaiKeAPIException {
        return null;
    }

    @Override
    public Map<String, Object> orderList(OrderVo vo) {
        return null;
    }

    @Override
    public Map<String, Object> remindDelivery(OrderVo vo) {
        return null;
    }

    @Override
    public Map<String, Object> cancleOrder(OrderVo vo) {
        return null;
    }

    @Override
    public Map<String, Object> loadMore(OrderVo vo) {
        return null;
    }

    @Override
    public Map<String, Object> delOrder(OrderVo vo) {
        return null;
    }

    @Override
    public Map<String, Object> buyAgain(BuyAgainVo vo) {
        return null;
    }

    @Override
    public Map<String, Object> orderSearch(OrderVo vo) {
        return null;
    }

    @Override
    public Map<String, Object> delCart(OrderVo vo) {
        return null;
    }

    @Override
    public Map<String, Object> getPaymentConf(OrderVo vo) {
        return null;
    }

    @Override
    public Map<String, Object> orderDetails(OrderVo vo) {
        return null;
    }

    @Override
    public Map<String, Object> showLogistics(OrderVo vo) {
        return null;
    }

    @Override
    public Map<String, Object> cancleApply(int storeId, int id) {
        return null;
    }

    @Override
    public Map<String, Object> returnOrderList(OrderVo vo) {
        return null;
    }

    @Override
    public Map<String, Object> okOrder(OrderVo orderVo) {
        return null;
    }

    @Override
    public Map<String, Object> returnMethod(OrderVo vo) {
        return null;
    }

    @Override
    public Map<String, Object> seeSend(int stroeId, int productId) {
        return null;
    }

    @Override
    public Map<String, Object> backSend(ReturnGoodsVo returnGoodsVo) {
        return null;
    }

    @Override
    public Map<String, Object> seeExtractionCode(OrderVo vo) {
        return null;
    }

    @Override
    public Map<String, Object> returndetails(RefundDetailsVo refundDetailsVo) {
        return null;
    }

    @Override
    public Map<String, Object> confirmReceipt(ReturnConfirmReceiptVo vo) {
        return null;
    }

    @Override
    public Map<String, Object> cancelApplication(CancleAfterSaleApplyVo params) {
        return null;
    }

    @Override
    public Map<String, Object> getPayment(OrderVo vo) {
        return null;
    }
}

